package com.liu.nb.handler;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.nb.util.AesEncryptUtil;
import com.liu.nb.util.Const;
import com.liu.nb.util.RedisUtil;
import com.liu.nb.util.exception.CaptchaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * @author lzy
 * @date 2021/10/15 星期五
 */

public class LoginByJsonFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            ObjectMapper mapper = new ObjectMapper();
            UsernamePasswordAuthenticationToken authRequest = null;
            Map<String,String> authenticationBean=null;
            try (InputStream is = request.getInputStream()) {
                authenticationBean = mapper.readValue(is, Map.class);
            } catch (IOException e) {
                e.printStackTrace();
                authRequest = new UsernamePasswordAuthenticationToken(
                        "", "");
            }
            /*
             * 在这里判断验证码是否正确
             * */
            String code=authenticationBean.get("captcha");
            String key=authenticationBean.get("token");
            //判断是否为空
            if (StringUtils.isBlank(code)&&StringUtils.isBlank(key)){
                throw new CaptchaException("验证码错误！");
            }
            //和redis中的验证码进行比较                                     开发阶段留个后门
            if ((!code.equals(redisUtil.hget(Const.CAPTCHA_KEY,key)))&&!code.equals("123456")){
                throw new CaptchaException("验证码错误！");
            }
            authRequest = new UsernamePasswordAuthenticationToken(authenticationBean.get("username"), AesEncryptUtil.desEncrypt(authenticationBean.get("password")));
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        else {
            return super.attemptAuthentication(request, response);
        }

    }
}
